<template>
	<view class="house-edit-page">
		<!-- 页面头部 -->
		<!-- 表单内容 -->
		<scroll-view class="form-container" scroll-y>
			<view class="form-content">
				<view class="form-section">
					<view class="section-title">基本信息</view>
					<uni-forms ref="houseForm" :modelValue="formData" :rules="formRules" :label-width="100">
						<!-- <uni-forms-item label="房源类型" name="propertyType" required>
							<uni-data-select
								v-model="formData.propertyType"
								:localdata="propertyTypeOptions"
								placeholder="请选择房源类型"
							></uni-data-select>
						</uni-forms-item> -->

						<view class="form-row">
							<uni-forms-item label="楼栋号" name="buildingNumber" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.buildingNumber" 
									placeholder="如：1"
									maxlength="10"
								/>
							</uni-forms-item>
							<uni-forms-item label="所在楼层" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.floor" 
									placeholder="如：5"
									type="number"
								/>
							</uni-forms-item>
							<uni-forms-item label="户号" required>
								<uni-easyinput
									v-model="formData.unitNumber" 
									placeholder="如：2"
									maxlength="20"
								/>
							</uni-forms-item>
							<!-- <uni-forms-item label="单元号" class="form-item-flex">
								<uni-easyinput 
									v-model="formData.unitNumber" 
									placeholder="如：1"
									maxlength="10"
								/>
							</uni-forms-item> -->
							<uni-forms-item label="房号" name="roomNumber"  required class="form-item-flex">
								<uni-easyinput 
						disabled v-model="formData.roomNumber" 
									placeholder="如：101"
									maxlength="10"
								/>
							</uni-forms-item>
							<uni-forms-item label="总楼层" class="form-item-flex">
								<uni-easyinput 
									v-model="formData.totalFloors" 
									placeholder="如：33"
									type="number"
								/>
							</uni-forms-item>
						</view>

						<view class="form-row">
							
							<uni-forms-item label="建筑面积(㎡)" name="area" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.area" 
									placeholder="如：89.5"
									type="digit"
								/>
							</uni-forms-item>
							<uni-forms-item label="套内面(㎡)" name="usableArea" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.usableArea" 
									placeholder="如：89.5"
									type="digit"
								/>
							</uni-forms-item>
						</view>

						

						<view class="form-row" >
							<uni-forms-item label="室" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.roomCount" 
									placeholder="如：3"
									type="number"
								/>
							</uni-forms-item>
							<uni-forms-item label="厅" class="form-item-flex" required>
								<uni-easyinput 
									v-model="formData.livingRoomCount" 
									placeholder="如：2"
									type="number"
								/>
							</uni-forms-item>
							<uni-forms-item label="卫" class="form-item-flex" required>
								<uni-easyinput 
									v-model="formData.bathroomCount" 
									placeholder="如：1"
									type="number"
								/>
							</uni-forms-item>
						</view>
						<uni-forms-item label="户型" name="roomLayout">
							<uni-easyinput  disabled
								v-model="formData.roomLayout" 
								placeholder="如：3室2厅1卫"
								maxlength="20"
							/>
						</uni-forms-item>
					</uni-forms>
				</view>

				<view class="form-section">
					<view class="section-title">房源特征</view>
					<uni-forms ref="houseForm" :modelValue="formData" :rules="formRules" :label-width="150">
						<!-- <view class="form-row">
							<uni-forms-item label="朝向" class="form-item-flex">
								<uni-data-select
									v-model="formData.orientation"
									:localdata="orientationOptions"
									placeholder="请选择朝向"
								></uni-data-select>
							</uni-forms-item>
							<uni-forms-item label="装修" class="form-item-flex">
								<uni-data-select
									v-model="formData.decoration"
									:localdata="decorationOptions"
									placeholder="请选择装修"
								></uni-data-select>
							</uni-forms-item>
						</view> -->

						<view class="form-row">
							<uni-forms-item label="单价(元/㎡)" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.unitPrice" 
									placeholder="如：15000"
									type="digit"
									@blur="calculateTotalPrice"
								/>
							</uni-forms-item>
							<uni-forms-item label="总价(元)" name="totalPrice" required class="form-item-flex">
								<uni-easyinput 
									v-model="formData.totalPrice" 
									placeholder="如：1342500"
									type="digit"
									@blur="calculateUnitPrice"
								/>
							</uni-forms-item>
							<uni-forms-item label="最低总价(元)" name="minPrice" required class="form-item-flex" v-if="$userInfo.role == 1">
								<uni-easyinput 
									v-model="formData.totalPrice" 
									placeholder="如：1342500"
									type="digit"
									@blur="calculateUnitPrice"
								/>
							</uni-forms-item>
						</view>

						<uni-forms-item label="房源描述">
							<uni-easyinput 
								v-model="formData.description" 
								placeholder="请输入房源描述信息"
								type="textarea"
								maxlength="500"
								:inputBorder="false"
							/>
						</uni-forms-item>
					</uni-forms>
				</view>

			<!-- 	<view class="form-section">
					<view class="section-title">房源图片</view>
					<view class="image-uploader">
						<view class="image-list">
							<view 
								v-for="(image, index) in formData.images" 
								:key="index"
								class="image-item"
							>
								<image :src="image" class="uploaded-image" mode="aspectFill"></image>
								<view class="image-actions">
									<uni-icons 
										type="clear" 
										size="20" 
										color="#fff" 
										@click="removeImage(index)"
									></uni-icons>
								</view>
							</view>
							<view class="upload-btn" @click="chooseImage" v-if="formData.images.length < 9">
								<uni-icons type="plus" size="32" color="#ccc"></uni-icons>
								<text class="upload-text">添加图片</text>
							</view>
						</view>
						<text class="upload-tip">最多可上传9张图片</text>
					</view>
				</view>

				<view class="form-section">
					<view class="section-title">其他信息</view>
					<uni-forms ref="houseForm" :modelValue="formData" :rules="formRules">
						<uni-forms-item label="推荐房源">
							<switch :checked="formData.isRecommend" @change="onRecommendChange" />
						</uni-forms-item>

						<uni-forms-item v-if="formData.isRecommend" label="推荐等级">
							<uni-data-select
								v-model="formData.recommendLevel"
								:localdata="recommendLevelOptions"
								placeholder="请选择推荐等级"
							></uni-data-select>
						</uni-forms-item>

						<uni-forms-item label="负责顾问">
							<uni-data-select
								v-model="formData.consultantId"
								:localdata="consultantOptions"
								placeholder="请选择负责顾问"
								@change="onConsultantChange"
							></uni-data-select>
						</uni-forms-item>
					</uni-forms>
				</view> -->

				<!-- 底部操作区域 -->
				<view class="form-actions">
					<button class="action-btn cancel-btn" @click="goBack">取消</button>
					<button class="action-btn save-btn-large" @click="saveHouse" :disabled="saving">
						{{ saving ? '保存中...' : '保存房源' }}
					</button>
				</view>

				<view class="form-bottom-space"></view>
			</view>
		</scroll-view>

		<!-- 成功提示 -->
		<uni-popup ref="successPopup" type="dialog">
			<uni-popup-dialog 
				type="success" 
				title="操作成功"
				:content="successMessage"
				@confirm="onSaveSuccess"
			></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 页面状态
				isEdit: false,
				houseId: '',
				saving: false,
				
				// 表单数据
				formData: {
					propertyName: '',
					propertyType: 1,
					buildingNumber: '',
					unitNumber: '',
					roomNumber: '',
					floor: 1,
					totalFloors: 1,
					area: '',
					usableArea:'',
					roomLayout: '',
					roomCount: '',
					livingRoomCount: '',
					bathroomCount: '',
					orientation: 2,
					decoration: 1,
					unitPrice: '',
					totalPrice: '',
					description: '',
					images: [],
					isRecommend: false,
					recommendLevel: 1,
					consultantId: '',
					consultantName: ''
				},
				
				// 表单验证规则
				formRules: {
					propertyName: {
						rules: [{
							required: true,
							errorMessage: '请输入房源名称'
						}]
					},
					propertyType: {
						rules: [{
							required: true,
							errorMessage: '请选择房源类型'
						}]
					},
					buildingNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入楼栋号'
						}]
					},
					roomNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入房号'
						}]
					},
					area: {
						rules: [{
							required: true,
							errorMessage: '请输入建筑面积'
						}]
					},
					totalPrice: {
						rules: [{
							required: true,
							errorMessage: '请输入总价'
						}]
					}
				},
				
				// 选项数据
				propertyTypeOptions: [
					{ value: 1, text: '住宅' },
					{ value: 2, text: '商铺' },
					{ value: 3, text: '写字楼' },
					{ value: 4, text: '别墅' },
					{ value: 5, text: '公寓' },
					{ value: 6, text: '车位' }
				],
				orientationOptions: [
					{ value: 1, text: '东' },
					{ value: 2, text: '南' },
					{ value: 3, text: '西' },
					{ value: 4, text: '北' },
					{ value: 5, text: '东南' },
					{ value: 6, text: '东北' },
					{ value: 7, text: '西南' },
					{ value: 8, text: '西北' }
				],
				decorationOptions: [
					{ value: 1, text: '毛坯' },
					{ value: 2, text: '简装' },
					{ value: 3, text: '精装' },
					{ value: 4, text: '豪装' }
				],
				recommendLevelOptions: [
					{ value: 1, text: '普通' },
					{ value: 2, text: '重点' },
					{ value: 3, text: '热销' }
				],
				consultantOptions: [],
				
				successMessage: ''
			}
		},
		watch: {
			// 监听房间数量变化
			'formData.roomCount': {
				handler() {
					this.watchRoomCounts();
				},
				immediate: false
			},
			'formData.livingRoomCount': {
				handler() {
					this.watchRoomCounts();
				},
				immediate: false
			},
			'formData.bathroomCount': {
				handler() {
					this.watchRoomCounts();
				},
				immediate: false
			},
			'formData.floor': {
				handler() {
					this.watchRoomNumber();
				},
				immediate: false
			},
			'formData.unitNumber': {
				handler() {
					this.watchRoomNumber();
				},
				immediate: false
			},
		},
		onLoad(options) {
			if (options.id) {
				this.isEdit = true;
				this.houseId = options.id;
				this.loadHouseDetail();
			}
			// this.loadConsultants();
		},
		methods: {
			watchRoomNumber() {
					const { floor, unitNumber } = this.formData;
					
					// 如果用户没有手动输入户型，且所有房间数量都有值，自动更新
					if (floor && unitNumber) {
						this.formData.roomNumber = `${floor<10?'0'+floor:floor}${unitNumber<10?'0'+unitNumber:unitNumber}`
					}
				},
			watchRoomCounts() {
					const { roomCount, livingRoomCount, bathroomCount } = this.formData;
					
					// 如果用户没有手动输入户型，且所有房间数量都有值，自动更新
					if (!this.formData.roomLayout && roomCount && livingRoomCount && bathroomCount) {
						this.formData.roomLayout = `${roomCount}室${livingRoomCount}厅${bathroomCount}卫`
					}
				},
			// 加载房源详情
			async loadHouseDetail() {
				try {
					const res = await this.$cloudOBjAjax('sunny-house', 'getHouseDetail', {
						houseId: this.houseId
					});
					
					if (res.code === 0) {
						this.formData = { ...res.data };
					} else {
						uni.showToast({
							title: '加载房源信息失败',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (err) {
					console.error('加载房源详情失败:', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},
			
			// 加载置业顾问列表
			async loadConsultants() {
				try {
					const res = await this.$cloudOBjAjax('sunny-users', 'getConsultantList');
					this.consultantOptions = res.data.map(item => ({
						value: item._id,
						text: item.name
					}));
				} catch (err) {
					console.error('加载顾问列表失败:', err);
				}
			},
			
			// 保存房源
			async saveHouse() {
				try {
					// 验证表单
					await this.$refs.houseForm.validate();
					
					this.saving = true;
					
					const method = this.isEdit ? 'updateHouse' : 'addHouse';
					const params = this.isEdit ? {
						houseId: this.houseId,
						...this.formData
					} : this.formData;
					
					const res = await this.$cloudOBjAjax('sunny-house', method, params);
					
					this.successMessage = this.isEdit ? '房源信息更新成功' : '房源添加成功';
					// this.$refs.successPopup.open();
					
				} catch (err) {
					if (err === 'validation') {
						uni.showToast({
							title: '请完善表单信息',
							icon: 'none'
						});
						return;
					}
					console.error('保存房源失败:', err);
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				} finally {
					this.saving = false;
				}
			},
			
			// 保存成功处理
			onSaveSuccess() {
				this.$refs.successPopup.close();
				uni.navigateBack();
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 选择图片
			async chooseImage() {
				try {
					const res = await uni.chooseImage({
						count: 9 - this.formData.images.length,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera']
					});
					
					// 这里应该上传图片到云存储并获取URL
					// 暂时直接使用临时路径
					this.formData.images = [...this.formData.images, ...res.tempFilePaths];
					
				} catch (err) {
					console.error('选择图片失败:', err);
				}
			},
			
			// 移除图片
			removeImage(index) {
				this.formData.images.splice(index, 1);
			},
			
			// 计算总价
			calculateTotalPrice() {
				if (this.formData.unitPrice && this.formData.area) {
					this.formData.totalPrice = Math.round(this.formData.unitPrice * this.formData.area);
				}
			},
			
			// 计算单价
			calculateUnitPrice() {
				if (this.formData.totalPrice && this.formData.area) {
					this.formData.unitPrice = Math.round(this.formData.totalPrice / this.formData.area);
				}
			},
			
			// 推荐状态变更
			onRecommendChange(e) {
				this.formData.isRecommend = e.detail.value;
			},
			
			// 顾问选择变更
			onConsultantChange(e) {
				const selected = this.consultantOptions.find(item => item.value === e);
				if (selected) {
					this.formData.consultantName = selected.text;
				}
			}
		}
	}
</script>

<style scoped>
	.house-edit-page {
		background-color: #f8f9fa;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	
	/* 页面头部 */
	.page-header {
		background: #fff;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}
	
	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.header-left {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.save-btn {
		background: #ff6b35;
		color: #fff;
		border: none;
		border-radius: 12rpx;
		padding: 16rpx 32rpx;
		font-size: 28rpx;
		font-weight: 500;
	}
	
	.save-btn:disabled {
		background: #ccc;
	}
	
	/* 表单容器 */
	.form-container {
		flex: 1;
		box-sizing: border-box;
	}
	
	.form-content {
		padding: 30rpx;
		box-sizing: border-box;
	}
	
	.form-section {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-sizing: border-box;
		width: 100%;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		padding-left: 20rpx;
		border-left: 8rpx solid #ff6b35;
	}
	
	.form-row {
		display: flex;
		gap: 20rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.form-item-flex {
		flex: 1;
		min-width: 0; /* 防止flex item溢出 */
	}
	
	/* 修复 uni-forms-item 样式 */
	:deep(.uni-forms-item) {
		width: 100%;
	}
	
	:deep(.uni-forms-item__container) {
		width: 100%;
	}
	
	:deep(.uni-forms-item__content) {
		display: flex;
		flex-direction: column;
	}
	
	:deep(.uni-easyinput) {
		width: 100%;
	}
	
	:deep(.uni-data-select) {
		width: 100%;
	}
	
	/* 图片上传 */
	.image-uploader {
		margin-top: 20rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 20rpx;
		width: 100%;
	}
	
	.image-item {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 12rpx;
		overflow: hidden;
		flex-shrink: 0;
	}
	
	.uploaded-image {
		width: 100%;
		height: 100%;
	}
	
	.image-actions {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		border: 2rpx dashed #e0e0e0;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		flex-shrink: 0;
	}
	
	.upload-text {
		font-size: 24rpx;
		color: #ccc;
	}
	
	.upload-tip {
		font-size: 24rpx;
		color: #999;
		text-align: center;
		display: block;
	}
	
	/* 表单操作 */
	.form-actions {
		display: flex;
		gap: 20rpx;
		padding: 40rpx 0;
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.action-btn {
		flex: 1;
		border: none;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 32rpx;
		font-weight: bold;
		box-sizing: border-box;
	}
	
	.cancel-btn {
		background: #f8f9fa;
		color: #666;
		border: 2rpx solid #e9ecef;
	}
	
	.save-btn-large {
		background: #ff6b35;
		color: #fff;
	}
	
	.save-btn-large:disabled {
		background: #ccc;
	}
	
	.form-bottom-space {
		height: 40rpx;
	}
	
	/* 修复文本域样式 */
	:deep(.uni-easyinput__content-textarea) {
		min-height: 120rpx;
	}
	
	/* 修复选择器样式 */
	:deep(.uni-select) {
		width: 100%;
	}
	
	:deep(.uni-select__input-text) {
		width: 100%;
	}
	
	/* 响应式调整 */
	@media (max-width: 750rpx) {
		.form-content {
			padding: 20rpx;
		}
		
		.form-section {
			padding: 20rpx;
		}
		
		.form-row {
			flex-direction: column;
			gap: 0;
		}
		
		.form-item-flex {
			width: 100%;
		}
		
		.image-item, .upload-btn {
			width: 140rpx;
			height: 140rpx;
		}
	}
</style>